package com.ruoyi.xuexiao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.constant.DataConstant;
import com.ruoyi.constant.v3.RwZtV3Enum;

import com.ruoyi.xuexiao.domain.entity.BasicRegion;
import com.ruoyi.xuexiao.domain.entity.RwTzV3;
import com.ruoyi.xuexiao.domain.param.SuperviseParam;
import com.ruoyi.xuexiao.domain.param.RwTzV3VParam;
import com.ruoyi.xuexiao.mapper.BasicRegionMapper;
import com.ruoyi.xuexiao.mapper.RwTzV3Mapper;
import com.ruoyi.xuexiao.service.AuditingService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 审核统计模块
 * @author 田江余
 */
@Service
@AllArgsConstructor
public class AuditingServiceImpl extends ServiceImpl<RwTzV3Mapper, RwTzV3> implements AuditingService {

    private RwTzV3Mapper rwTzV3Mapper;

    private BasicRegionMapper basicRegionMapper;

    private BasicRegionMapper BasicRegionMapper;


    /**
     * 审核统计
     * 上下半年统计
     * @author 田江余
     * @param
     * @return
     */
    @Override
    public Map<String,Object> selectRwTzVYear(RwTzV3VParam rwTzV3Vo) {
        Map<String, Object> map = new HashMap<>();
        //上半年
        List<RwTzV3VParam> selectRwTzV3 = rwTzV3Mapper.selectRwTz(rwTzV3Vo);
        //下半年
        List<RwTzV3VParam> selectRwTzV3Year = rwTzV3Mapper.selectRw(rwTzV3Vo);
        map.put("selectRwTzV3",selectRwTzV3);
        map.put("selectRwTzV3Year",selectRwTzV3Year);

        return  map ;
    }

    /**
     * 审核统计
     * 上下半年省级核查任务进度
     * @author 田江余
     *
     * @param
     * @return
     */
    @Override
    public List<RwTzV3VParam> InTheFirstHalfOfTh(RwTzV3VParam rwTzV3Vo) {
        ArrayList<RwTzV3VParam> rwTzV3DTOS = new ArrayList<>();

        LambdaQueryWrapper<RwTzV3> rwTzV3LambdaQueryWrapper = getRwTzV3LambdaQueryWrapper(1,1);
        Long sl = rwTzV3Mapper.selectCount(rwTzV3LambdaQueryWrapper);
        extracted(sl,rwTzV3DTOS);

        LambdaQueryWrapper<RwTzV3> tzV3LambdaQueryWrapper = getRwTzV3LambdaQueryWrapper(1,2);
        Long xl = rwTzV3Mapper.selectCount(tzV3LambdaQueryWrapper);
        extracted(xl,rwTzV3DTOS);

        return rwTzV3DTOS;
    }

    /**
     * 查询条件
     * @author 田江余
     */
    private static LambdaQueryWrapper<RwTzV3> getRwTzV3LambdaQueryWrapper(Integer rwjb,Integer sxbn) {
        LambdaQueryWrapper<RwTzV3> rwTzV3LambdaQueryWrapper = new LambdaQueryWrapper<>();
        //任务数量
        rwTzV3LambdaQueryWrapper.eq(RwTzV3::getRwjb, rwjb);
        //上半年
        rwTzV3LambdaQueryWrapper.eq(RwTzV3::getSxbn,sxbn);
        //已审核
        rwTzV3LambdaQueryWrapper.in(RwTzV3::getRwzt, RwZtV3Enum.getAi());
        return rwTzV3LambdaQueryWrapper;
    }

    /**
     * 计算封装数据
     * @author 田江余
     */
    private void extracted(Long sum,ArrayList<RwTzV3VParam> rwTzV3DTOS) {
        RwTzV3VParam rwTzV3DTO = new RwTzV3VParam();
        //审核百分比
        double reportPercentage = (double) rwTzV3DTOS.size() / sum * 100;
        rwTzV3DTO.setTotalRwsl(sum);//任务数量
        rwTzV3DTO.setYtb(rwTzV3DTOS.size());//已审核
        rwTzV3DTO.setBfb(Math.round(reportPercentage));//审核百分比，取整，不要小数点
        rwTzV3DTOS.add(rwTzV3DTO);
    }

    /**
     * 上半年市级核查任务进度
     * @author 田江余
     */
    @Override
    public List<RwTzV3VParam> inTheSecondHalfOfYear(ArrayList<RwTzV3VParam> rwTzV3Vo, SuperviseParam supervise) {
        // 任务数量
        LambdaQueryWrapper<RwTzV3> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //上下半年，1,2
        lambdaQueryWrapper.eq(RwTzV3::getSxbn,supervise.getYear());
        //1是省，2是市，3是县
        lambdaQueryWrapper.eq(RwTzV3::getRwjb, 2);
        Long sl = rwTzV3Mapper.selectCount(lambdaQueryWrapper);

        // 已审核
        LambdaQueryWrapper<RwTzV3> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(RwTzV3::getRwzt, RwZtV3Enum.getAi());
        // 查询已审核的任务列表
        List<RwTzV3> rwTzV3s = rwTzV3Mapper.selectList(wrapper);
        // 创建一个新的列表来存储查询结果
        List<RwTzV3VParam> resultDTOs = new ArrayList<>();
        // 用于存储每个市的任务数量和审核数量
        Map<String, RwTzV3VParam> cityTaskAndSubmissionCountMap = new HashMap<>();
        for (RwTzV3 rwTzV3 : rwTzV3s) {
            // 市名称
            String sjcs = basicRegionMapper.selectOne(
                    new LambdaQueryWrapper<BasicRegion>()
                            .eq(BasicRegion::getAdcd, rwTzV3.getSxzqdm())
            ).getAdnm();
            // 检查市名称是否已经存在于结果列表中
            if (!cityTaskAndSubmissionCountMap.containsKey(sjcs)) {
                // 创建一个新的RwTzV3DTO对象来存储当前市的信息
                RwTzV3VParam rwTzV3DTO = new RwTzV3VParam();
                // 审核数量
                rwTzV3DTO.setYtb(rwTzV3Vo.size());
                // 任务数量
                rwTzV3DTO.setTotalRwsl(sl);
                // 市名称
                rwTzV3DTO.setSjcs(sjcs);
                // 将当前市的信息添加到结果列表中
                resultDTOs.add(rwTzV3DTO);
                // 将市名称添加到map中
                cityTaskAndSubmissionCountMap.put(sjcs, rwTzV3DTO);
            }
            // 增加任务数量和审核数量
            RwTzV3VParam cityInfo = cityTaskAndSubmissionCountMap.get(sjcs);
            cityInfo.setTotalRwsl(cityInfo.getTotalRwsl() + 1);
            cityInfo.setYtb(cityInfo.getYtb() + 1);

            double percent = cityInfo.getYtb() / (double)cityInfo.getTotalRwsl() * 100;
            // 向下取整
            int wholeNumberBfb = (int) Math.floor(percent);
            // 现在bfb字段只有整数部分，没有小数点
            cityInfo.setBfb(wholeNumberBfb);
        }
        // 返回查询结果列表
        return resultDTOs;
    }

    /**
     * 上/下半年县级核查任务进度
     * @author 田江余
     * @param
     * @return
     */
    @Override
    public List<BasicRegion> inTheSecondHalf(SuperviseParam supervise) {
        // 查询所有数据
        List<BasicRegion> BasicRegione = BasicRegionMapper.selectList(null);
        // 过滤出所有市级行政区
        List<BasicRegion> cityRegions = BasicRegione.stream()
                .filter(r -> r.getLevel() == DataConstant.REGION_LEVEL_OF_CITY)
                .collect(Collectors.toList());

        // 合并数据库查询
        Map<String, BasicRegion> cityRegionMap = cityRegions.stream()
                .collect(Collectors.toMap(BasicRegion::getAdcd, Function.identity()));
        // 为每个市级行政区设置其下一级的县级行政区列表
        List<BasicRegion> cityAndCountyRegions = cityRegions.stream()
                .map(city -> {
                    city.setChild(BasicRegione.stream()
                            .filter(r -> {
                                int i = r.getAdcd().length() - 2;
                                boolean f = (r.getAdcd().substring(0, i) + "00").equals(city.getAdcd());
                                return r.getLevel() == DataConstant.REGION_LEVEL_OF_COUNTY && f;
                            })
                            .collect(Collectors.toList()));
                    return city;
                })
                .collect(Collectors.toList());

        // 查询所有县级行政区
        List<BasicRegion> countyRegions = basicRegionMapper.selectList(new LambdaQueryWrapper<BasicRegion>()
                .eq(BasicRegion::getLevel, DataConstant.REGION_LEVEL_OF_COUNTY));

        // 获取所有县级行政区的代码
        List<String> countyCodes = countyRegions.stream()
                .map(BasicRegion::getAdcd)
                .collect(Collectors.toList());

        // 批量查询县级行政区数量和特定状态的县级行政区数量
        List<RwTzV3> rwTzV3List = rwTzV3Mapper.selectList(new LambdaQueryWrapper<RwTzV3>()
                .in(RwTzV3::getSxbn, supervise.getYear())
                .in(RwTzV3::getXxzqdm, countyCodes)
                .in(RwTzV3::getRwzt, RwZtV3Enum.getAi()));

        // 统计数量
        Map<String, Long> rwTzV3CountListMap = rwTzV3List.stream()
                .collect(Collectors.groupingBy(RwTzV3::getXxzqdm, Collectors.counting()));
        // 更新BasicRegions对象
        cityRegionMap.values().forEach(cityRegion -> {
            for (BasicRegion basicRegion : cityRegion.getChild()) {
                basicRegion.setTotalRwsl(rwTzV3CountListMap.getOrDefault(basicRegion.getAdcd(), 0L));
                basicRegion.setYtb(rwTzV3CountListMap.getOrDefault(basicRegion.getAdcd(), 0L));
                if (basicRegion.getTotalRwsl() > 0) { // 确保totalRwsl不为0，避免除以0的错误
                    basicRegion.setBfb((basicRegion.getYtb().doubleValue() / basicRegion.getTotalRwsl()) * 100);
                } else {
                    basicRegion.setBfb(0.0); // 如果totalRwsl为0，则bfb为0
                }
            }
            //过滤为0的数据
            List<BasicRegion> basicRegions = cityRegion.getChild().stream().filter(e -> e.getTotalRwsl() != 0).collect(Collectors.toList());
            cityRegion.setChild(basicRegions);
            //计算市相加数量
            cityRegion.setTotalRwsl(basicRegions.stream().mapToLong(BasicRegion::getTotalRwsl).sum());
            cityRegion.setYtb(basicRegions.stream().mapToLong(BasicRegion::getYtb).sum());
            // 确保totalRwsl不为0，避免除以0的错误
            if (cityRegion.getTotalRwsl() > 0) {
                cityRegion.setBfb((cityRegion.getYtb().doubleValue() / cityRegion.getTotalRwsl()) * 100);
            } else {
                cityRegion.setBfb(0.0); // 如果totalRwsl为0，则bfb为0
            }
        });
        return cityAndCountyRegions;
    }

}
